<?php

namespace App\Model;

use App\BaseModel;
use Illuminate\Support\Facades\DB;

class VisitByDate extends BaseModel
{
    protected $table = "sys_visit_by_date";

    public static function updateToday($type)
    {

    }

    public static function updateYesterday($type)
    {

    }

    //type
    public static function updateByDate($date,$type)
    {

        $whereSql = ' and created_at >="'.$date.' 00:00:00" and created_at <="'.$date.' 23:59:59" ';

        $sql = [];

        //二维码来源浏览量
        $sql[0] = 'select count(id) as total from sys_visits where obj_type='.$type.' and origin=1 '.$whereSql;

        //二维码来源浏览人数
        $sql[1] = 'select count(user_id) as total from (select user_id from sys_visits where obj_type='.$type.' 
                and origin=1 '.$whereSql.' group by user_id) con';

        //普通来源浏览量
        $sql[2] = 'select count(id) as total from sys_visits where obj_type='.$type.' and origin=0 '. $whereSql;

        //普通来源浏览人数
        $sql[3] = 'select count(user_id) as total from (select user_id from sys_visits where obj_type='.$type.' 
                and origin=0 '.$whereSql.' group by user_id) con';

        $rows = [];
        $total = 0; //葡萄酒详情页总浏览量

        foreach ($sql as $k=>$v){
            $res = DB::select($v);
            $rows[$k] = $res[0]->total;
            $total += $res[0]->total;
        }

        return VisitByDate::updateOrCreate(['date'=>$date,'obj_type'=>$type],[
            'total' => $total,
            'qr_pv' => $rows[0],
            'qr_uv' => $rows[1],
            'pv' => $rows[2],
            'uv' => $rows[3],
        ]);

    }
}
